package com.zxy.ziems.server.board.service.impl;

import com.zxy.btp.common.response.PageResult;
import com.zxy.btp.web.util.TokenUtils;
import com.zxy.ziems.server.board.convertor.RoleFileConvertor;
import com.zxy.ziems.server.board.mapper.RoleFileMapper;
import com.zxy.ziems.server.board.pojo.dto.RoleFileDTO;
import com.zxy.ziems.server.board.pojo.entity.RoleFileEntity;
import com.zxy.ziems.server.board.pojo.vo.RoleFileVo;
import com.zxy.ziems.server.board.service.RoleFileService;
import com.zxy.ziems.server.file.entity.FileEntity;
import com.zxy.ziems.server.file.service.FileService;
import com.zxy.ziems.server.file.vo.FileVO;
import com.zxy.ziems.server.mybatis.core.pojo.PageParam;
import com.zxy.ziems.server.mybatis.core.service.ServiceImplX;
import com.zxy.ziems.server.utils.AssertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class RoleFileServiceImpl extends ServiceImplX<RoleFileMapper, RoleFileEntity> implements RoleFileService {

    @Autowired
    private FileService fileService;

    @Transactional
    @Override
    public void addRoleFile(RoleFileDTO roleFileDTO) {
        RoleFileEntity roleFileEntity = RoleFileConvertor.INSTANT.typeDTOConvertor2Entity(roleFileDTO);
        baseMapper.insert(roleFileEntity);
    }


    @Override
    public PageResult<RoleFileVo> getRoleFile(PageParam pageParam) {
        String curUserName = TokenUtils.getUserNameByToken();
        PageResult<RoleFileVo> pageResult = customPage(pageParam, (page, aParam) -> baseMapper.pageUserFile(page, curUserName));
        if (pageResult.getTotal() > 0) {
            Set<String> fileIdSet = pageResult.getList().stream().map(RoleFileVo::getFileId).collect(Collectors.toSet());
            List<FileEntity> fileEntities = fileService.listByIds(fileIdSet);
            Map<String, FileEntity> fileMap = fileEntities.stream().collect(Collectors.toMap(FileEntity::getId, v -> v));
            pageResult.getList().stream().forEach(m -> {
                FileVO fileVo = FileVO.makeBy(fileMap.get(m.getFileId()));
                m.setFile(fileVo);
            });
        }

        return pageResult;
    }

    @Transactional
    @Override
    public void removeFile(String roleFileId) {
        RoleFileEntity entity = getById(roleFileId);
        AssertUtil.nonNull(entity, "未找到文件或已删除");
        this.removeById(roleFileId);
        fileService.removeById(entity.getFileId());
    }
}
